package com.agileai.crm.controller.customer;

import java.util.ArrayList;
import java.util.List;

import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONObject;

import com.agileai.crm.bizmoduler.customer.CustomerGroup8ContentManage;
import com.agileai.crm.bizmoduler.customer.CustomerSalesPersonnelInfoSelect;
import com.agileai.crm.bizmoduler.system.SecurityAuthorizationConfig;
import com.agileai.domain.DataParam;
import com.agileai.domain.DataRow;
import com.agileai.hotweb.annotation.PageAction;
import com.agileai.hotweb.controller.core.TreeSelectHandler;
import com.agileai.hotweb.domain.TreeBuilder;
import com.agileai.hotweb.renders.AjaxRenderer;
import com.agileai.hotweb.renders.LocalRenderer;
import com.agileai.hotweb.renders.ViewRenderer;
import com.agileai.util.StringUtil;

public class CustomerSalesPersonnelInfoSelectHandler
        extends TreeSelectHandler {
	private static final String ROLE_SALES_ID = "8AAF1DCF-114D-49D4-B691-A46F77288AF0";
	
    public CustomerSalesPersonnelInfoSelectHandler() {
        super();
        this.serviceId = buildServiceId(CustomerSalesPersonnelInfoSelect.class);
        this.isMuilSelect = true;
        this.checkRelParentNode = false;
        this.mulSelectNodeTypes.add("Object");
    }

	public ViewRenderer prepareDisplay(DataParam param){
		this.setAttributes(param);
		return new LocalRenderer(getPage());
	}    
    
    protected TreeBuilder provideTreeBuilder(DataParam param) {
        return null;
    }
    
    
	@PageAction
	public ViewRenderer retrieveJson(DataParam param){
		String responseText = FAIL;
		try {
			JSONArray jsonArray = new JSONArray();
			String id = param.get("id",ROLE_SALES_ID);
			
			CustomerSalesPersonnelInfoSelect customerSalesPersonnelInfoSelect = this.getService();
	    	List<DataRow> records = customerSalesPersonnelInfoSelect.findChildGroupRecords(id);
			records = customerSalesPersonnelInfoSelect.queryPickTreeRecords(new DataParam("roleId",id));
			if (records != null && !records.isEmpty()){
				List<String> existUserIds = getExistUserIds(param);
				for (int i=0 ;i < records.size();i++){
					DataRow row = records.get(i);
					String userId = row.stringValue("USER_ID");
					if (existUserIds.contains(userId)){
						continue;
					}
					String userName = row.stringValue("USER_NAME");
					JSONObject jsonObject = new JSONObject();
					jsonObject.put("id",userId);
					jsonObject.put("text",userName);
					jsonArray.put(jsonObject);
				}					
			}
			responseText = jsonArray.toString();
		} catch (Exception e) {
			log.error(e);
		}
		return new AjaxRenderer(responseText);
	}
	
	private List<String> getExistUserIds(DataParam param){
		String resourceType = param.get("resourceType");
    	String resourceId = param.get("resourceId");
    	List<String> existUserIds = new ArrayList<String>();
    	if (StringUtil.isNotNullNotEmpty(resourceType) && StringUtil.isNotNullNotEmpty(resourceId)){
        	SecurityAuthorizationConfig securityAuthorizationConfig = lookupService(SecurityAuthorizationConfig.class);
        	List<DataRow> existsRecords = securityAuthorizationConfig.retrieveUserList(resourceType, resourceId);
        	for (int i=0;i < existsRecords.size();i++){
        		DataRow row = existsRecords.get(i);
        		String userId = row.stringValue("USER_ID");
        		if (existUserIds.contains(userId)){
        			continue;
        		}
        		existUserIds.add(userId);
        	}
    	}else{
    		String custId = param.get("custId");
    		if (StringUtil.isNotNullNotEmpty(custId)){
    			CustomerGroup8ContentManage CustomerGCM = this.lookupService(CustomerGroup8ContentManage.class);
    			List<DataRow> existsRecords = CustomerGCM.findRecords(new DataParam("custId",custId));
            	for (int i=0;i < existsRecords.size();i++){
            		DataRow row = existsRecords.get(i);
            		String userId = row.stringValue("USER_ID");
            		if (existUserIds.contains(userId)){
            			continue;
            		}
            		existUserIds.add(userId);
            	}
    		}
    	}
    	return existUserIds;
	}
	
    @PageAction
    public ViewRenderer addUserRequest(DataParam param){
    	return this.prepareDisplay(param);
    }    
    
    protected CustomerSalesPersonnelInfoSelect getService() {
        return (CustomerSalesPersonnelInfoSelect) this.lookupService(this.getServiceId());
    }
}
